<template>
	<view>
		<view class="container" v-if='certificateContent && certificateContent.length > 0'>
			<canvas canvas-id="certCanvas" :style="imageStyle" />
			<image v-if="resultImage" :src="resultImage" mode="widthFix" class="result-image" />
			<u-button v-if="resultImage" @click="saveToAlbum" type="primary" shape='circle'>下载证书</u-button>
		</view>
		<view v-else>
			<view style='color:#19be6b;text-align: center;padding:10px'>请填写下列内容，以便生成您的电子证书</view>
			<view v-if='inputData && inputData.length > 0'>
				<view v-for='item in inputData'>
					<view style='margin:5px;color:#606266'>{{item.name}}</view>
					<view>
						<u--input placeholder="请输入内容" border="surround" v-model="item.value"></u--input>
					</view>
				</view>
			</view>
			<view style='margin-top:30px'>
				<u-button text='保存并生成证书' type='primary' shape='circle' @click='saveData'></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				resultImage: '',
				bgImage: '',
				certificateContent: [],
				inputData: [],
				textData: {
					
				},
				textClolr: '#FFD700',
				imageWidth: 1280, // 图片宽度
				imageHeight: 904, // 图片高度
				textX: 905, // 文字开始的X坐标
				textY: 900, // 文字开始的Y坐标
				maxWidth: 800, // 单行最大宽度
				linepacing: 60, //行距
				fontSize: 42, // 字体大小
				textAlign: 'left', // 字对齐方式,
				imageStyle: `width:1280px;height:904px;position:fixed;left:-9999px`
			}
		},
		onLoad(options) {
			if (typeof(options.id) != 'undefined') {
				uni.showLoading()
				this.request.get(`api/user-coupons/${options.id}`, {
					'@expands': `['entity.coupon.region']`
				}, ).then((res) => {
					if (res.data) {
						this.userCoupon = res.data
						console.log(this.userCoupon)
						if (res.data.coupon.__metadata.region.__metadata.extraData && res.data.coupon.__metadata
							.region.__metadata.extraData.cardImage) {
							this.bgImage = res.data.coupon.__metadata.region.__metadata.extraData.cardImage
							// 查看是否配置了相关的样式，有的就覆盖，无就用默认的
							if(res.data.coupon.__metadata.region.__metadata.extraData){
								this.textClolr = res.data.coupon.__metadata.region.__metadata.extraData.textClolr ? res.data.coupon.__metadata.region.__metadata.extraData.textClolr : '#FFD700'
								this.imageWidth = res.data.coupon.__metadata.region.__metadata.extraData.imageWidth ? res.data.coupon.__metadata.region.__metadata.extraData.imageWidth : 1810
								this.imageHeight = res.data.coupon.__metadata.region.__metadata.extraData.imageHeight ? res.data.coupon.__metadata.region.__metadata.extraData.imageHeight : 1280
								this.textX = res.data.coupon.__metadata.region.__metadata.extraData.textX ? res.data.coupon.__metadata.region.__metadata.extraData.textX : 905
								this.textY = res.data.coupon.__metadata.region.__metadata.extraData.textY ? res.data.coupon.__metadata.region.__metadata.extraData.textY : 900
								this.maxWidth = res.data.coupon.__metadata.region.__metadata.extraData.maxWidth ? res.data.coupon.__metadata.region.__metadata.extraData.maxWidth : 800
								this.linepacing = res.data.coupon.__metadata.region.__metadata.extraData.linepacing ? res.data.coupon.__metadata.region.__metadata.extraData.linepacing : 60
								this.fontSize = res.data.coupon.__metadata.region.__metadata.extraData.fontSize ? res.data.coupon.__metadata.region.__metadata.extraData.fontSize : 42
								this.textAlign = res.data.coupon.__metadata.region.__metadata.extraData.textAlign ? res.data.coupon.__metadata.region.__metadata.extraData.textAlign : 'left'
								this.imageStyle = `width:${this.imageWidth}px;height:${this.imageHeight}px;position:fixed;left:-9999px`
							}
							// 查是否已经写了内容，没有的，需要先写
							if (res.data.extraData && res.data.extraData.certificateContent) {
								this.certificateContent = res.data.extraData.certificateContent
								
								this.initCanvas();
							} else {
								if (res.data.coupon.__metadata.region.__metadata.extraData && res.data.coupon
									.__metadata.region.__metadata.extraData.data) {
									console.log('需要填写内容', res.data.coupon.__metadata.region.__metadata.extraData
										.data)
									let inputData = []
									for (let i of res.data.coupon.__metadata.region.__metadata.extraData.data) {
										i.value = ''
										inputData.push(i)
										this.inputData = inputData
										uni.hideLoading()
									}
								} else {
									uni.hideLoading()
									uni.showModal({
										title: '',
										content: '证书设置有误，请联系客服咨询！',
										showCancel: false,
										success: () => {
											uni.switchTab({
												url: '/pages/index/index'
											})
										}
									})
								}
							}
						} else {
							uni.hideLoading()
							uni.showModal({
								title: '',
								content: '未设置电子证书，请联系客服咨询！',
								showCancel: false,
								success: () => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							})
						}
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '',
							content: '参数错误，请重试！',
							showCancel: false,
							success: () => {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						})
					}
				})
			} else {
				uni.hideLoading()
				uni.showModal({
					title: '',
					content: '参数错误，请重试！',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			}
		},
		methods: {
			async initCanvas() {
				try {
					// 1. 加载图片
					const {
						path
					} = await new Promise((resolve, reject) => {
						uni.getImageInfo({
							src: this.bgImage,
							success: resolve,
							fail: reject
						});
					});

					// 2. 创建绘图上下文
					const ctx = uni.createCanvasContext('certCanvas', this);

					// 3. 绘制背景
					ctx.drawImage(path, 0, 0, this.imageWidth, this.imageHeight);

					// 4. 设置文字样式
					ctx.setFontSize(this.fontSize);
					ctx.setFillStyle(this.textClolr);
					ctx.setTextAlign(this.textAlign);

					// 5. 绘制文字
					let yPos = this.textY;
					this.certificateContent.forEach((text, i) => {
						yPos = this.wrapText(ctx, text, this.textX, yPos, this.maxWidth, this.linepacing);
						yPos += this.linepacing;
					});

					// 6. 关键修正：使用setTimeout确保绘制完成
					ctx.draw(true, () => {
						setTimeout(() => {
							uni.canvasToTempFilePath({
								canvasId: 'certCanvas',
								success: (res) => {
									uni.hideLoading()
									this.resultImage = res.tempFilePath;
								},
								fail: console.error
							});
						}, 300);
					});

				} catch (err) {
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
				}
			},
			wrapText(ctx, text, x, y, maxWidth, lineHeight) {
				const words = text.split('');
				let line = '';

				for (let i = 0; i < words.length; i++) {
					const testLine = line + words[i];
					const metrics = ctx.measureText(testLine);

					if (metrics.width > maxWidth && i > 0) {
						ctx.fillText(line, x, y);
						line = words[i];
						y += lineHeight;
					} else {
						line = testLine;
					}
				}
				ctx.fillText(line, x, y);
				return y;
			},
			saveToAlbum() {
				if (!this.resultImage) return;

				this.saving = true;
				uni.saveImageToPhotosAlbum({
					filePath: this.resultImage,
					success: () => {
						uni.showToast({
							title: '保存成功'
						});
					},
					complete: () => {
						this.saving = false;
					}
				});
			},
			saveData() {
				console.log(this.inputData)
				for (let i of this.inputData) {
					if (i.value.trim() == "") {
						uni.showModal({
							title: '',
							content: `请填写${i.name}`,
							showCancel: false,
							success: () => {}
						})
						return
					}
				}
				uni.showModal({
					title: '',
					content: '一旦保存将不能修改，是否确认保存？',
					success: (data) => {
						if (data.confirm) {
							let certificateContent = []
							for (let i in this.inputData) {
								if(certificateContent.length == 0 || (this.inputData[i].isLineBreak &&  this.inputData[i].isLineBreak== true)){
									certificateContent.push(`${this.inputData[i].beforeText}${this.inputData[i].value}${this.inputData[i].afterText}`)
								}else{
									certificateContent[i-1] += `${this.inputData[i].beforeText}${this.inputData[i].value}${this.inputData[i].afterText}`
								}
							}
							console.log(certificateContent)
							this.certificateContent = certificateContent
							this.request.put(`api/user-coupons/${this.userCoupon.id}`, {
								extraData: {
									certificateContent: certificateContent
								}
							})
							this.initCanvas();
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		min-height: 100vh;
	}

	.result-image {
		width: 100%;
		margin-bottom: 40rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.save-btn {
		width: 80%;
		margin-top: 20rpx;
	}
</style>